<template>
  <view class="address-search">
    <!-- 搜索框 -->
    <view class="search-container">
      <u-search
        v-model="searchKeyword"
        placeholder="请输入地址"
        :show-action="false"
        @input="onSearchInput"
        @search="onSearch"
        :clearabled="true"
      ></u-search>
    </view>

    <!-- 搜索结果列表 -->
    <view class="search-results" v-if="searchResults.length > 0">
      <view 
        class="result-item" 
        v-for="(item, index) in searchResults" 
        :key="index"
        @click="selectAddress(item)"
      >
        <view class="main-text">{{ item.structured_formatting.main_text }}</view>
        <view class="secondary-text">{{ item.structured_formatting.secondary_text }}</view>
      </view>
    </view>

    <!-- 无结果提示 -->
    <view class="no-results" v-if="searchKeyword && searchResults.length === 0 && !isLoading">
      <text>未找到相关地址</text>
    </view>

    <!-- 加载提示 -->
    <view class="loading" v-if="isLoading">
      <u-loading mode="circle"></u-loading>
      <text>搜索中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      isLoading: false,
      searchTimer: null,
      googleApiKey: 'AIzaSyBzxlFg6KHf8BPje--mzix0O_ThZ-sA3vs', // 需要替换为实际的Google API Key
    };
  },
  onLoad() {
    uni.setNavigationBarTitle({
      title: '选择地址'
    });
  },
  methods: {
    // 搜索输入处理
    onSearchInput(value) {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      
      // 设置新的定时器，延迟搜索
      this.searchTimer = setTimeout(() => {
        if (value && value.length > 2) {
          this.searchAddress(value);
        } else {
          this.searchResults = [];
        }
      }, 300);
    },

    // 搜索按钮点击
    onSearch(value) {
      if (value && value.length > 0) {
        this.searchAddress(value);
      }
    },

    // 调用Google Places API搜索地址
    async searchAddress(query) {
      this.isLoading = true;
      
      try {
        const response = await uni.request({
          url: 'https://maps.googleapis.com/maps/api/place/autocomplete/json',
          method: 'GET',
          data: {
            input: query,
            key: this.googleApiKey
            // 移除types限制，允许更多类型的地点
            // 移除country限制，允许全球搜索
          }
        });
        
        // uni.request 在某些平台返回 [null, response] 格式的数据
        const responseData = Array.isArray(response) ? response[1] : response;
        
        console.log('搜索结果:', responseData);
        
        if (responseData.data && responseData.data.predictions && responseData.data.predictions.length > 0) {
          this.searchResults = responseData.data.predictions;
          console.log('找到地址数量:', this.searchResults.length);
        } else {
          this.searchResults = [];
          console.log('未找到地址，状态:', responseData.data ? responseData.data.status : '未知');
          if (responseData.data && responseData.data.status !== 'OK') {
            uni.showToast({
              title: '搜索失败: ' + responseData.data.status,
              icon: 'none',
              duration: 3000
            });
          }
        }
      } catch (error) {
        console.error('搜索地址失败:', error);
        uni.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
        this.searchResults = [];
      } finally {
        this.isLoading = false;
      }
    },

    // 选择地址
    async selectAddress(item) {
      console.log('选择的地址项:', item);
      
      // 使用place_id获取详细地址信息
      if (item.place_id) {
        await this.getPlaceDetails(item.place_id);
      } else {
        // 如果没有place_id，使用原来的解析方法
        this.parseAddressFromDescription(item);
      }
    },
    
    // 获取地点详细信息
    async getPlaceDetails(placeId) {
      try {
        uni.showLoading({
          title: '获取地址详情...'
        });
        
        const response = await uni.request({
          url: 'https://maps.googleapis.com/maps/api/place/details/json',
          method: 'GET',
          data: {
            place_id: placeId,
            key: this.googleApiKey,
            language: 'zh-CN',
            fields: 'formatted_address,address_components,geometry'
          }
        });
        
        const responseData = Array.isArray(response) ? response[1] : response;
        
        if (responseData.data && responseData.data.result) {
          const result = responseData.data.result;
          const addressComponents = result.address_components || [];
          
          // 解析地址组件
          let country = '';
          let province = '';
          let city = '';
          let postalCode = '';
          let formattedAddress = result.formatted_address || '';
          
          addressComponents.forEach(component => {
            const types = component.types;
            
            if (types.includes('country')) {
              country = component.long_name;
            } else if (types.includes('administrative_area_level_1')) {
              province = component.long_name;
            } else if (types.includes('locality') || types.includes('administrative_area_level_2')) {
              city = component.long_name;
            } else if (types.includes('postal_code')) {
              postalCode = component.long_name;
            }
          });
          
          console.log('详细地址信息:', {
            address: formattedAddress,
            country,
            province,
            city,
            postalCode
          });
          
          this.setAddressData({
            address: formattedAddress,
            addressNo: postalCode,
            country: country,
            province: province,
            city: city,
            addressCity: city,
            addressProvince: province,
            addressCountry: country
          });
        } else {
          throw new Error('无法获取地址详情');
        }
      } catch (error) {
        console.error('获取地址详情失败:', error);
        uni.showToast({
          title: '获取地址详情失败，使用基本信息',
          icon: 'none'
        });
        // 降级到原来的解析方法
        this.parseAddressFromDescription(item);
      } finally {
        uni.hideLoading();
      }
    },
    
    // 从描述中解析地址（降级方案）
    parseAddressFromDescription(item) {
      const formattedAddress = item.description || item.structured_formatting.main_text + ', ' + item.structured_formatting.secondary_text;
      
      // 尝试从地址描述中提取邮编
      let postalCode = '';
      
      // 检查描述中是否包含"邮政编码:"或"邮编:"字样
      if (formattedAddress.includes('邮政编码:') || formattedAddress.includes('邮编:')) {
        const match = formattedAddress.match(/邮政编码:\s*([A-Z0-9\s]+)($|\s|,)|邮编:\s*([A-Z0-9\s]+)($|\s|,)/);
        if (match) {
          postalCode = (match[1] || match[3]).trim();
        }
      } else if (formattedAddress.includes('M1P') || formattedAddress.includes('L1P') || formattedAddress.includes('H3C')) {
        const match = formattedAddress.match(/([A-Z][0-9][A-Z]\s*[0-9][A-Z][0-9])/);
        if (match) {
          postalCode = match[1];
        }
      }
      
      // 解析地址组件
      let country = '';
      let province = '';
      let city = '';
      
      const addressParts = formattedAddress.split(',').map(part => part.trim());
      if (addressParts.length >= 3) {
        country = addressParts[addressParts.length - 1].replace(/\s*邮政编码:.*$/, '').trim();
        province = addressParts[addressParts.length - 2].trim();
        city = addressParts[addressParts.length - 3].trim();
      }
      
      this.setAddressData({
        address: formattedAddress,
        addressNo: postalCode,
        country: country,
        province: province,
        city: city,
        addressCity: city,
        addressProvince: province,
        addressCountry: country
      });
    },
    
    // 设置地址数据并返回上一页
    setAddressData(addressData) {
      console.log('设置地址数据:', addressData);
      
      // 返回到上一页并传递数据
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      
      if (prevPage && prevPage.$vm && prevPage.$vm.form) {
        // 设置上一页的数据
        Object.assign(prevPage.$vm.form, addressData);
        console.log('已设置上一页数据');
      } else {
        console.error('无法获取上一页或上一页没有form对象');
        // 如果无法直接设置上一页数据，使用事件通信
        uni.$emit('address_selected', addressData);
      }
      
      // 返回上一页
      uni.navigateBack();
    }
  },

  onUnload() {
    // 清除定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  }
};
</script>

<style scoped>
.address-search {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.search-container {
  margin-bottom: 20rpx;
}

.search-results {
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
}

.result-item {
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.result-item:last-child {
  border-bottom: none;
}

.result-item:active {
  background-color: #f5f5f5;
}

.main-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
}

.secondary-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}

.no-results {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.loading text {
  margin-top: 20rpx;
}
</style>